import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:intl/intl.dart';

import '../models/calendar_event.dart';
import '../providers/calendar_providers.dart';

/// 添加或编辑日历事件的对话框
class AddEventDialog extends ConsumerStatefulWidget {
  /// 要编辑的事件（如果为null则表示添加新事件）
  final CalendarEvent? eventToEdit;

  /// 构造函数
  const AddEventDialog({Key? key, this.eventToEdit}) : super(key: key);

  @override
  ConsumerState<AddEventDialog> createState() => _AddEventDialogState();
}

class _AddEventDialogState extends ConsumerState<AddEventDialog> {
  final _formKey = GlobalKey<FormState>();
  final _titleController = TextEditingController();
  final _descriptionController = TextEditingController();
  final _locationController = TextEditingController();
  final _participantsController = TextEditingController();
  
  late DateTime _startDate;
  late TimeOfDay _startTime;
  late DateTime _endDate;
  late TimeOfDay _endTime;
  late CalendarEventType _eventType;
  bool _isAllDay = false;
  bool _isRecurring = false;
  String? _recurrenceType;
  int? _reminderMinutes;

  @override
  void initState() {
    super.initState();
    
    // 如果是编辑模式，则使用现有事件的数据初始化表单
    if (widget.eventToEdit != null) {
      final event = widget.eventToEdit!;
      _titleController.text = event.title;
      _descriptionController.text = event.description;
      _locationController.text = event.location ?? '';
      _participantsController.text = event.participants?.join(', ') ?? '';
      
      _startDate = event.startTime;
      _startTime = TimeOfDay(hour: event.startTime.hour, minute: event.startTime.minute);
      
      if (event.endTime != null) {
        _endDate = event.endTime!;
        _endTime = TimeOfDay(hour: event.endTime!.hour, minute: event.endTime!.minute);
      } else {
        _endDate = event.startTime.add(const Duration(hours: 1));
        _endTime = TimeOfDay(hour: _endDate.hour, minute: _endDate.minute);
      }
      
      _eventType = event.eventType;
      _isAllDay = event.isAllDay;
      _isRecurring = event.isRecurring;
      _recurrenceType = event.recurrenceType;
      _reminderMinutes = event.reminderMinutes;
    } else {
      // 添加新事件，使用默认值
      final now = DateTime.now();
      _startDate = now;
      _startTime = TimeOfDay.now();
      _endDate = now.add(const Duration(hours: 1));
      _endTime = TimeOfDay(hour: (TimeOfDay.now().hour + 1) % 24, minute: TimeOfDay.now().minute);
      _eventType = CalendarEventType.other;
    }
  }

  @override
  void dispose() {
    _titleController.dispose();
    _descriptionController.dispose();
    _locationController.dispose();
    _participantsController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: Text(widget.eventToEdit == null ? '添加新事件' : '编辑事件'),
      content: SingleChildScrollView(
        child: Form(
          key: _formKey,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 事件类型选择器
              DropdownButtonFormField<CalendarEventType>(
                decoration: const InputDecoration(labelText: '事件类型'),
                value: _eventType,
                items: CalendarEventType.values.map((type) {
                  return DropdownMenuItem<CalendarEventType>(
                    value: type,
                    child: Row(
                      children: [
                        Icon(type.icon.icon, color: type.color, size: 20),
                        const SizedBox(width: 8),
                        Text(_getEventTypeName(type)),
                      ],
                    ),
                  );
                }).toList(),
                onChanged: (value) {
                  if (value != null) {
                    setState(() {
                      _eventType = value;
                    });
                  }
                },
              ),
              const SizedBox(height: 16),
              
              // 标题输入框
              TextFormField(
                controller: _titleController,
                decoration: const InputDecoration(labelText: '标题'),
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请输入事件标题';
                  }
                  return null;
                },
              ),
              const SizedBox(height: 16),
              
              // 描述输入框
              TextFormField(
                controller: _descriptionController,
                decoration: const InputDecoration(labelText: '描述'),
                maxLines: 3,
              ),
              const SizedBox(height: 16),
              
              // 全天事件开关
              SwitchListTile(
                title: const Text('全天事件'),
                value: _isAllDay,
                onChanged: (value) {
                  setState(() {
                    _isAllDay = value;
                  });
                },
                contentPadding: EdgeInsets.zero,
              ),
              
              // 开始日期和时间选择器
              Row(
                children: [
                  Expanded(
                    child: InkWell(
                      onTap: () => _selectStartDate(context),
                      child: InputDecorator(
                        decoration: const InputDecoration(labelText: '开始日期'),
                        child: Text(
                          DateFormat('yyyy-MM-dd').format(_startDate),
                        ),
                      ),
                    ),
                  ),
                  const SizedBox(width: 16),
                  if (!_isAllDay)
                    Expanded(
                      child: InkWell(
                        onTap: () => _selectStartTime(context),
                        child: InputDecorator(
                          decoration: const InputDecoration(labelText: '开始时间'),
                          child: Text(
                            _startTime.format(context),
                          ),
                        ),
                      ),
                    ),
                ],
              ),
              const SizedBox(height: 16),
              
              // 结束日期和时间选择器
              Row(
                children: [
                  Expanded(
                    child: InkWell(
                      onTap: () => _selectEndDate(context),
                      child: InputDecorator(
                        decoration: const InputDecoration(labelText: '结束日期'),
                        child: Text(
                          DateFormat('yyyy-MM-dd').format(_endDate),
                        ),
                      ),
                    ),
                  ),
                  const SizedBox(width: 16),
                  if (!_isAllDay)
                    Expanded(
                      child: InkWell(
                        onTap: () => _selectEndTime(context),
                        child: InputDecorator(
                          decoration: const InputDecoration(labelText: '结束时间'),
                          child: Text(
                            _endTime.format(context),
                          ),
                        ),
                      ),
                    ),
                ],
              ),
              const SizedBox(height: 16),
              
              // 地点输入框
              TextFormField(
                controller: _locationController,
                decoration: const InputDecoration(labelText: '地点（可选）'),
              ),
              const SizedBox(height: 16),
              
              // 参与者输入框
              TextFormField(
                controller: _participantsController,
                decoration: const InputDecoration(
                  labelText: '参与者（可选，用逗号分隔）',
                ),
              ),
              const SizedBox(height: 16),
              
              // 重复事件开关
              SwitchListTile(
                title: const Text('重复事件'),
                value: _isRecurring,
                onChanged: (value) {
                  setState(() {
                    _isRecurring = value;
                    if (!value) {
                      _recurrenceType = null;
                    } else if (_recurrenceType == null) {
                      _recurrenceType = 'daily';
                    }
                  });
                },
                contentPadding: EdgeInsets.zero,
              ),
              
              // 重复类型选择器
              if (_isRecurring)
                DropdownButtonFormField<String>(
                  decoration: const InputDecoration(labelText: '重复类型'),
                  value: _recurrenceType ?? 'daily',
                  items: [
                    DropdownMenuItem(value: 'daily', child: Text('每天')),
                    DropdownMenuItem(value: 'weekly', child: Text('每周')),
                    DropdownMenuItem(value: 'monthly', child: Text('每月')),
                    DropdownMenuItem(value: 'yearly', child: Text('每年')),
                  ],
                  onChanged: (value) {
                    if (value != null) {
                      setState(() {
                        _recurrenceType = value;
                      });
                    }
                  },
                ),
              const SizedBox(height: 16),
              
              // 提醒时间选择器
              DropdownButtonFormField<int?>(
                decoration: const InputDecoration(labelText: '提醒'),
                value: _reminderMinutes,
                items: [
                  const DropdownMenuItem(value: null, child: Text('不提醒')),
                  const DropdownMenuItem(value: 0, child: Text('事件开始时')),
                  const DropdownMenuItem(value: 15, child: Text('提前15分钟')),
                  const DropdownMenuItem(value: 30, child: Text('提前30分钟')),
                  const DropdownMenuItem(value: 60, child: Text('提前1小时')),
                  const DropdownMenuItem(value: 120, child: Text('提前2小时')),
                  const DropdownMenuItem(value: 1440, child: Text('提前1天')),
                ],
                onChanged: (value) {
                  setState(() {
                    _reminderMinutes = value;
                  });
                },
              ),
            ],
          ),
        ),
      ),
      actions: [
        TextButton(
          onPressed: () => Navigator.of(context).pop(),
          child: const Text('取消'),
        ),
        ElevatedButton(
          onPressed: _saveEvent,
          child: Text(widget.eventToEdit == null ? '添加' : '保存'),
        ),
      ],
    );
  }

  /// 选择开始日期
  Future<void> _selectStartDate(BuildContext context) async {
    final picked = await showDatePicker(
      context: context,
      initialDate: _startDate,
      firstDate: DateTime(2020),
      lastDate: DateTime(2030),
    );
    
    if (picked != null) {
      setState(() {
        _startDate = DateTime(
          picked.year,
          picked.month,
          picked.day,
          _startTime.hour,
          _startTime.minute,
        );
        
        // 如果开始日期晚于结束日期，则更新结束日期
        if (_startDate.isAfter(_endDate)) {
          _endDate = _startDate.add(const Duration(hours: 1));
          _endTime = TimeOfDay(hour: _endDate.hour, minute: _endDate.minute);
        }
      });
    }
  }

  /// 选择开始时间
  Future<void> _selectStartTime(BuildContext context) async {
    final picked = await showTimePicker(
      context: context,
      initialTime: _startTime,
    );
    
    if (picked != null) {
      setState(() {
        _startTime = picked;
        _startDate = DateTime(
          _startDate.year,
          _startDate.month,
          _startDate.day,
          picked.hour,
          picked.minute,
        );
        
        // 如果开始时间晚于结束时间，则更新结束时间
        final startDateTime = DateTime(
          _startDate.year,
          _startDate.month,
          _startDate.day,
          _startTime.hour,
          _startTime.minute,
        );
        
        final endDateTime = DateTime(
          _endDate.year,
          _endDate.month,
          _endDate.day,
          _endTime.hour,
          _endTime.minute,
        );
        
        if (startDateTime.isAfter(endDateTime)) {
          _endDate = _startDate;
          _endTime = TimeOfDay(
            hour: (_startTime.hour + 1) % 24,
            minute: _startTime.minute,
          );
        }
      });
    }
  }

  /// 选择结束日期
  Future<void> _selectEndDate(BuildContext context) async {
    final picked = await showDatePicker(
      context: context,
      initialDate: _endDate,
      firstDate: _startDate,
      lastDate: DateTime(2030),
    );
    
    if (picked != null) {
      setState(() {
        _endDate = DateTime(
          picked.year,
          picked.month,
          picked.day,
          _endTime.hour,
          _endTime.minute,
        );
      });
    }
  }

  /// 选择结束时间
  Future<void> _selectEndTime(BuildContext context) async {
    final picked = await showTimePicker(
      context: context,
      initialTime: _endTime,
    );
    
    if (picked != null) {
      setState(() {
        _endTime = picked;
        _endDate = DateTime(
          _endDate.year,
          _endDate.month,
          _endDate.day,
          picked.hour,
          picked.minute,
        );
        
        // 如果结束时间早于开始时间且日期相同，则调整结束时间
        if (_endDate.day == _startDate.day &&
            _endDate.month == _startDate.month &&
            _endDate.year == _startDate.year &&
            _endTime.hour < _startTime.hour) {
          _endDate = _endDate.add(const Duration(days: 1));
        }
      });
    }
  }

  /// 保存事件
  void _saveEvent() {
    if (_formKey.currentState!.validate()) {
      // 构建开始和结束时间
      final startDateTime = _isAllDay
          ? DateTime(_startDate.year, _startDate.month, _startDate.day)
          : DateTime(
              _startDate.year,
              _startDate.month,
              _startDate.day,
              _startTime.hour,
              _startTime.minute,
            );
      
      final endDateTime = _isAllDay
          ? DateTime(_endDate.year, _endDate.month, _endDate.day, 23, 59, 59)
          : DateTime(
              _endDate.year,
              _endDate.month,
              _endDate.day,
              _endTime.hour,
              _endTime.minute,
            );
      
      // 处理参与者列表
      List<String>? participants;
      if (_participantsController.text.isNotEmpty) {
        participants = _participantsController.text
            .split(',')
            .map((e) => e.trim())
            .where((e) => e.isNotEmpty)
            .toList();
      }
      
      // 如果是编辑现有事件
      if (widget.eventToEdit != null) {
        final updatedEvent = widget.eventToEdit!.copyWith(
          title: _titleController.text,
          description: _descriptionController.text,
          startTime: startDateTime,
          endTime: endDateTime,
          eventType: _eventType,
          location: _locationController.text.isEmpty ? null : _locationController.text,
          participants: participants,
          isAllDay: _isAllDay,
          isRecurring: _isRecurring,
          recurrenceType: _isRecurring ? _recurrenceType : null,
          reminderMinutes: _reminderMinutes,
        );
        
        ref.read(calendarEventsProvider.notifier).updateEvent(updatedEvent);
      } else {
        // 创建新事件
        ref.read(calendarEventsProvider.notifier).createEvent(
              title: _titleController.text,
              description: _descriptionController.text,
              startTime: startDateTime,
              endTime: endDateTime,
              eventType: _eventType,
              location: _locationController.text.isEmpty ? null : _locationController.text,
              participants: participants,
              isAllDay: _isAllDay,
              isRecurring: _isRecurring,
              recurrenceType: _isRecurring ? _recurrenceType : null,
              reminderMinutes: _reminderMinutes,
            );
      }
      
      Navigator.of(context).pop();
    }
  }

  /// 获取事件类型名称
  String _getEventTypeName(CalendarEventType eventType) {
    switch (eventType) {
      case CalendarEventType.birthday:
        return '生日';
      case CalendarEventType.play:
        return '游玩';
      case CalendarEventType.medical:
        return '看病';
      case CalendarEventType.anniversary:
        return '纪念日';
      case CalendarEventType.familyGathering:
        return '家庭聚会';
      case CalendarEventType.study:
        return '学习';
      case CalendarEventType.other:
        return '其他';
      default:
        return '未知';
    }
  }
}
